package pool;

public class TestPC {
	public static void main(String[] args) {
		SynContainer container = new SynContainer();
		new Productor(container).start();
		new Consumer(container).start();

	}
}

//生产者
class Productor extends Thread {
	SynContainer container;

	public Productor(SynContainer container) {
		this.container = container;
	}

	@Override
	public void run() {
		synchronized (container) {
			for (int i = 1; i < 100; i++) {
				container.push(new Chicken(i));
				System.out.println("生产了" + i + "只鸡");
			}
		}

	}
}

//消费者
class Consumer extends Thread {
	SynContainer container;

	public Consumer(SynContainer container) {
		this.container = container;
	}

	@Override
	public void run() {

		for (int i = 1; i < 102; i++) {
			System.out.println("消费了第" + container.pop().id + "只鸡");

		}
	}
}

//产品
class Chicken extends Thread {
	int id;

	public Chicken(int id) {
		this.id = id;
	}
}

//缓冲区
class SynContainer {
	Chicken[] chickens = new Chicken[10];
	int count = 0;

	//生产者生产产品
	public synchronized void push(Chicken chicken) {
		if (count == chickens.length) {
			//可以消费了
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//否则不能消费 ,继续生产
		chickens[count] = chicken;
		count++;
		//消费者
		this.notifyAll();
	}

	//消费者消费产品
	public synchronized Chicken pop() {
		if (count == 0) {
			//说明没有产品，等待消费者消费
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//否则就是有产品。可以直接消费
		count--;
		Chicken chicken = chickens[count];
		//
		this.notifyAll();
		return chicken;
	}

}
